<?php
/**
 * version 1.0.0
 * 日志文件
 */
namespace App\Helps;

class LogHelper
{
    /**
     * 写入 错误日志
     * @param $path
     * @param $message
     * @param $data
     * @return
     */
    static public function error($path, $message, $data) {
        $log_file = self::createLogFile($path,"error");
        $message = self::contentFormat($message, $data);
        file_put_contents($log_file, $message );
    }

    /**
     * 写入 信息日志
     * @param $path
     * @param $message
     * @param $data
     * @return
     */
    static public function info($path, $message, $data) {
        $log_file = self::createLogFile($path,"info");
        $message = self::contentFormat($message, $data);
        file_put_contents($log_file, $message."\r\n", FILE_APPEND );
    }

    /**
     * 写入 警告日志
     * @param $path
     * @param $message
     * @param $data
     * @return
     */
    static public function warning($path, $message, $data) {
        $log_file = self::createLogFile($path,"warning");
        $message = self::contentFormat($message, $data);
        file_put_contents($log_file, $message."\r\n", FILE_APPEND );
    }

    /**
     * 写入 追踪日志
     * @param $path
     * @param $message
     * @param $data
     * @return
     */
    static public function trace($path, $message, $data) {
        $log_file = self::createLogFile($path,"trace");
        $message = self::contentFormat($message, $data);
        file_put_contents($log_file, $message."\r\n", FILE_APPEND );
    }

    /**
     * 创建日志文件
     * @param $fileName // 自定义文件路径
     * @param $tag // 标识
     * @return
     */
    static public function createLogFile($fileName, $tag) {
        $ext = $tag.".log";
        $path = storage_path()."/logs/".$fileName."/";
        //创建日志目录
        if(!file_exists($path)){
            mkdir($path,0777,true);
        }
        //创建日志文件
        if(!file_exists($path.$ext)){
            fopen($path.$ext,'a');
        }
        return $path.$ext;
    }

    /**
     * 创建日志文件
     * @param $msg
     * @param $data
     * @return
     */
    static public function contentFormat($msg, $data) {
        $message['msg'] = $msg;
        $message['data'] = $data;
        $message['time'] = date("Y-m-d H:i:s", time());
        return json_encode($message,500);
    }

}
